package server.user;
import server.user.User;
import server.order.Order;
import java.sql.SQLException;
import java.sql.ResultSet;
import server.Logger;

public class Admin extends User {
	public Admin(String username, String password) throws BadUserException, SQLException{
		super(username,password);
		if(!isAdmin()){
			throw new BadUserException("User is not admin!");
		}
	}
	
	/**
	 * @return An array of non-admin users
	 */
	public User[] fetchUsers(){
		String query = "SELECT id FROM "+User.TABLE+" WHERE "+ADMIN+"=0";
		try{
			ResultSet rs = doQuery(query);
			rs.last();
			User users[] = new User[rs.getRow()];
			rs.first();
			int count = 0;
			do{		
				users[count++] = new User(rs.getInt("id")); 
			} while (rs.next());
			return users;
		} catch(SQLException e){
			Logger.getInstance().addSQLQueryError("SQL Error Listing Users", query, 2);
			return new User[0];
		}		
	}
	
	/**
	 * @return An array of all open orders
	 */
	public Order[] fetchOpenOrders(){
		String query = "SELECT id FROM "+Order.TABLE+" WHERE "+Order.CLOSE_TIME+"=0";
		try{
			ResultSet rs = doQuery(query);
			rs.last();
			Order orders[] = new Order[rs.getRow()];
			rs.first();
			int count = 0;
			do{		
				orders[count++] = new Order(rs.getInt("id")); 
			} while (rs.next());
			return orders;
		} catch(SQLException e){
			Logger.getInstance().addSQLQueryError("SQL Error Listing Orders", query, 2);
			return new Order[0];
		}
	}
	
	/**
	 * Return the user with the specified id
	 * @param id	User ID
	 * @return	User
	 * @throws SQLException
	 */
	public User fetchUser(int id) throws SQLException{
		return new User(id);
	}
}